<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>{{ isViewMode ? '能力评估详情' : '长者能力评估' }}</span>
          <div class="right-buttons">
            <el-button v-if="currentStep > 0 && !isViewMode" type="primary" plain @click="prevStep">上一步</el-button>
            <el-button v-if="currentStep < steps.length - 1 && !isViewMode" type="primary" @click="nextStep">下一步</el-button>
            <el-button v-if="currentStep === steps.length - 1 && !isViewMode" type="success" @click="submitForm">提交</el-button>
            <el-button @click="cancel">{{ isViewMode ? '返回' : '取消' }}</el-button>
          </div>
        </div>
      </template>

      <!-- 成功提交显示 -->
      <div v-if="showSuccessMessage" class="success-message">
        <el-result icon="success" title="长者能力评估数据提交成功">
          <template #extra>
            <div class="countdown-container">
              <el-progress
                type="circle"
                :percentage="countdownPercentage"
                :stroke-width="6"
                :width="100"
                status="success"
              >
                <template #default>
                  <div class="countdown-text">
                    <span>{{ countdown }}秒后</span>
                    <span>返回列表</span>
                  </div>
                </template>
              </el-progress>
            </div>
            <div class="mt-4">
              <el-button type="primary" @click="handleReturnToList">立即返回</el-button>
            </div>
          </template>
        </el-result>
      </div>

      <!-- 步骤内容 -->
      <div v-else>
        <!-- 进度条 -->
        <el-progress
          v-if="!isViewMode"
          :percentage="progressPercentage"
          :text-inside="true"
          :stroke-width="20"
          status="success"
          style="margin: 15px 0;"
        />

        <!-- 步骤条 -->
        <el-steps v-if="!isViewMode" :active="currentStep" finish-status="success" class="mb-4">
          <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description" />
        </el-steps>

        <!-- 步骤内容区域 -->
        <div class="step-content">
          <!-- 步骤1：基本信息 -->
          <div v-show="currentStep === 0">
            <el-form ref="basicInfoFormRef" :model="form" :rules="rules" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="老人姓名" prop="elderName">
                    <el-select
                      v-model="form.elderName"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入老人姓名搜索"
                      :remote-method="searchElders"
                      :loading="searchLoading"
                      style="width: 100%"
                      @change="handleElderChange"
                      :disabled="isViewMode"
                      no-data-text="请输入老人姓名进行搜索"
                    >
                      <el-option
                        v-for="item in elderOptions"
                        :key="item.elderId"
                        :label="item.elderName"
                        :value="item.elderName"
                      >
                        <div class="flex justify-between">
                          <span>{{ item.elderName }}</span>
                          <span class="text-gray-400">{{ item.roomNumber || '未分配房间' }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="评估日期" prop="assessDate">
                    <el-date-picker
                      v-model="form.assessDate"
                      type="datetime"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="评估日期"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="评估人" prop="assessor">
                    <el-input
                      v-model="form.assessor"
                      placeholder="请输入评估人姓名"
                      :disabled="isViewMode || (isNurseUser && !isAdminUser)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 步骤2：日常生活能力 -->
          <div v-show="currentStep === 1">
            <div class="assessment-section">
              <h3 class="section-title">日常生活能力评估</h3>
              <div class="assessment-content">
                <el-form ref="dailyLivingFormRef" :model="form" :rules="rules" label-width="150px">
                  <!-- 自理能力 -->
                  <el-form-item label="自理能力" prop="selfCare">
                    <el-radio-group v-model="form.selfCare" :disabled="isViewMode">
                      <el-radio label="完全自理(10分)">完全自理</el-radio>
                      <el-radio label="基本自理(8分)">基本自理</el-radio>
                      <el-radio label="轻度依赖(6分)">轻度依赖</el-radio>
                      <el-radio label="中度依赖(4分)">中度依赖</el-radio>
                      <el-radio label="重度依赖(2分)">重度依赖</el-radio>
                      <el-radio label="完全依赖(0分)">完全依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 行动能力 -->
                  <el-form-item label="行动能力" prop="mobility">
                    <el-radio-group v-model="form.mobility" :disabled="isViewMode">
                      <el-radio label="行走自如(10分)">行走自如</el-radio>
                      <el-radio label="轻度受限(8分)">轻度受限</el-radio>
                      <el-radio label="需要辅助工具(6分)">需要辅助工具</el-radio>
                      <el-radio label="需要他人帮助(4分)">需要他人帮助</el-radio>
                      <el-radio label="行动极为困难(2分)">行动极为困难</el-radio>
                      <el-radio label="卧床不起(0分)">卧床不起</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 进食能力 -->
                  <el-form-item label="进食能力" prop="eating">
                    <el-radio-group v-model="form.eating" :disabled="isViewMode">
                      <el-radio label="完全自理(10分)">完全自理</el-radio>
                      <el-radio label="需要一些帮助(8分)">需要一些帮助</el-radio>
                      <el-radio label="需要较多帮助(6分)">需要较多帮助</el-radio>
                      <el-radio label="大部分需要帮助(4分)">大部分需要帮助</el-radio>
                      <el-radio label="几乎不能自理(2分)">几乎不能自理</el-radio>
                      <el-radio label="完全依赖(0分)">完全依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>

          <!-- 步骤3：个人卫生能力 -->
          <div v-show="currentStep === 2">
            <div class="assessment-section">
              <h3 class="section-title">个人卫生能力评估</h3>
              <div class="assessment-content">
                <el-form ref="hygieneFormRef" :model="form" :rules="rules" label-width="150px">
                  <!-- 穿衣能力 -->
                  <el-form-item label="穿衣能力" prop="dressing">
                    <el-radio-group v-model="form.dressing" :disabled="isViewMode">
                      <el-radio label="完全自理(10分)">完全自理</el-radio>
                      <el-radio label="需要一些帮助(8分)">需要一些帮助</el-radio>
                      <el-radio label="需要较多帮助(6分)">需要较多帮助</el-radio>
                      <el-radio label="大部分需要帮助(4分)">大部分需要帮助</el-radio>
                      <el-radio label="几乎不能自理(2分)">几乎不能自理</el-radio>
                      <el-radio label="完全依赖(0分)">完全依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 如厕能力 -->
                  <el-form-item label="如厕能力" prop="toileting">
                    <el-radio-group v-model="form.toileting" :disabled="isViewMode">
                      <el-radio label="完全自理(10分)">完全自理</el-radio>
                      <el-radio label="需要一些帮助(8分)">需要一些帮助</el-radio>
                      <el-radio label="需要较多帮助(6分)">需要较多帮助</el-radio>
                      <el-radio label="大部分需要帮助(4分)">大部分需要帮助</el-radio>
                      <el-radio label="几乎不能自理(2分)">几乎不能自理</el-radio>
                      <el-radio label="完全依赖(0分)">完全依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 洗澡能力 -->
                  <el-form-item label="洗澡能力" prop="bathing">
                    <el-radio-group v-model="form.bathing" :disabled="isViewMode">
                      <el-radio label="完全自理(10分)">完全自理</el-radio>
                      <el-radio label="需要一些帮助(8分)">需要一些帮助</el-radio>
                      <el-radio label="需要较多帮助(6分)">需要较多帮助</el-radio>
                      <el-radio label="大部分需要帮助(4分)">大部分需要帮助</el-radio>
                      <el-radio label="几乎不能自理(2分)">几乎不能自理</el-radio>
                      <el-radio label="完全依赖(0分)">完全依赖</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>

          <!-- 步骤4：认知与沟通能力 -->
          <div v-show="currentStep === 3">
            <div class="assessment-section">
              <h3 class="section-title">认知与沟通能力评估</h3>
              <div class="assessment-content">
                <el-form ref="cognitiveFormRef" :model="form" :rules="rules" label-width="150px">
                  <!-- 认知能力 -->
                  <el-form-item label="认知能力" prop="cognitive">
                    <el-radio-group v-model="form.cognitive" :disabled="isViewMode">
                      <el-radio label="完全正常(10分)">完全正常</el-radio>
                      <el-radio label="轻度障碍(8分)">轻度障碍</el-radio>
                      <el-radio label="中度障碍(6分)">中度障碍</el-radio>
                      <el-radio label="重度障碍(4分)">重度障碍</el-radio>
                      <el-radio label="严重障碍(2分)">严重障碍</el-radio>
                      <el-radio label="极重度障碍(0分)">极重度障碍</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 沟通能力 -->
                  <el-form-item label="沟通能力" prop="communication">
                    <el-radio-group v-model="form.communication" :disabled="isViewMode">
                      <el-radio label="表达清晰(10分)">表达清晰</el-radio>
                      <el-radio label="表达基本清晰(8分)">表达基本清晰</el-radio>
                      <el-radio label="表达有障碍(6分)">表达有障碍</el-radio>
                      <el-radio label="表达困难(4分)">表达困难</el-radio>
                      <el-radio label="表达极为困难(2分)">表达极为困难</el-radio>
                      <el-radio label="无法表达(0分)">无法表达</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 记忆力 -->
                  <el-form-item label="记忆力" prop="memory">
                    <el-radio-group v-model="form.memory" :disabled="isViewMode">
                      <el-radio label="记忆力良好(10分)">记忆力良好</el-radio>
                      <el-radio label="轻微遗忘(8分)">轻微遗忘</el-radio>
                      <el-radio label="经常遗忘(6分)">经常遗忘</el-radio>
                      <el-radio label="严重遗忘(4分)">严重遗忘</el-radio>
                      <el-radio label="几乎无记忆(2分)">几乎无记忆</el-radio>
                      <el-radio label="完全无记忆(0分)">完全无记忆</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>

          <!-- 步骤5：社交与情绪 -->
          <div v-show="currentStep === 4">
            <div class="assessment-section">
              <h3 class="section-title">社交与情绪评估</h3>
              <div class="assessment-content">
                <el-form ref="socialFormRef" :model="form" :rules="rules" label-width="150px">
                  <!-- 社交能力 -->
                  <el-form-item label="社交能力" prop="social">
                    <el-radio-group v-model="form.social" :disabled="isViewMode">
                      <el-radio label="社交活跃(10分)">社交活跃</el-radio>
                      <el-radio label="社交正常(8分)">社交正常</el-radio>
                      <el-radio label="社交减少(6分)">社交减少</el-radio>
                      <el-radio label="社交困难(4分)">社交困难</el-radio>
                      <el-radio label="社交极少(2分)">社交极少</el-radio>
                      <el-radio label="社交缺失(0分)">社交缺失</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 情绪状态 -->
                  <el-form-item label="情绪状态" prop="emotion">
                    <el-radio-group v-model="form.emotion" :disabled="isViewMode">
                      <el-radio label="情绪稳定(10分)">情绪稳定</el-radio>
                      <el-radio label="情绪基本稳定(8分)">情绪基本稳定</el-radio>
                      <el-radio label="情绪波动(6分)">情绪波动</el-radio>
                      <el-radio label="情绪不稳定(4分)">情绪不稳定</el-radio>
                      <el-radio label="情绪问题较多(2分)">情绪问题较多</el-radio>
                      <el-radio label="情绪严重问题(0分)">情绪严重问题</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 睡眠质量 -->
                  <el-form-item label="睡眠质量" prop="sleep">
                    <el-radio-group v-model="form.sleep" :disabled="isViewMode">
                      <el-radio label="睡眠良好(10分)">睡眠良好</el-radio>
                      <el-radio label="偶尔失眠(8分)">偶尔失眠</el-radio>
                      <el-radio label="经常失眠(6分)">经常失眠</el-radio>
                      <el-radio label="睡眠困难(4分)">睡眠困难</el-radio>
                      <el-radio label="严重失眠(2分)">严重失眠</el-radio>
                      <el-radio label="几乎不能入睡(0分)">几乎不能入睡</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>

          <!-- 步骤6：评估结果 -->
          <div v-show="currentStep === 5">
            <div class="assessment-section">
              <h3 class="section-title">评估结果与护理建议</h3>
              <div class="assessment-content">
                <el-form ref="summaryFormRef" :model="form" :rules="rules" label-width="150px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="总分" prop="totalScore">
                        <el-input-number v-model="form.totalScore" :min="0" :max="100" :disabled="true" style="width: 100%" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="护理等级" prop="careLevel">
                        <el-input v-model="form.careLevel" :disabled="true" style="width: 100%" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="护理建议" prop="suggestions">
                        <el-input
                          v-model="form.suggestions"
                          type="textarea"
                          :rows="4"
                          placeholder="系统根据评估结果自动生成护理建议"
                          :disabled="true"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="备注" prop="remarks">
                        <el-input
                          v-model="form.remarks"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入备注信息"
                          :disabled="isViewMode"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <!-- 能力评估结果图表 -->
                <div class="assessment-chart">
                  <h4>能力评估雷达图</h4>
                  <div class="chart-container">
                    <!-- 这里可以放置雷达图组件，暂时用文字代替 -->
                    <div class="ability-summary">
                      <div class="ability-item" v-for="(score, ability) in abilityScores" :key="ability">
                        <span class="ability-name">{{ getAbilityLabel(ability) }}</span>
                        <el-progress :percentage="getScorePercentage(score)" :stroke-width="10" :status="getScoreStatus(score)" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="AbilityAssessmentStep" lang="ts">
import { listAbilityAssessment, getAbilityAssessment, addAbilityAssessment, updateAbilityAssessment } from '@/api/nursing/abilityAssessment';
import { listElderBasic } from '@/api/nursing/elderBasic';
import { AbilityAssessmentVO, AbilityAssessmentForm } from '@/api/nursing/abilityAssessment/types';
import { ElderBasicVO } from '@/api/nursing/elderBasic/types';
import { getCurrentInstance, computed, ref, reactive, onMounted, onUnmounted } from 'vue';
import type { FormRules, FormInstance } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const userStore = useUserStoreHook();

// 倒计时变量
const countdown = ref(5); // 5秒倒计时
const showSuccessMessage = ref(false);
let countdownTimer: number | null = null;

// 查看模式标志
const isViewMode = computed(() => route.query.mode === 'view');

// 用户角色判断
const isNurseUser = computed(() => userStore.roles.some(role => role === 'nursing'));
const isAdminUser = computed(() => userStore.roles.some(role => role === 'admin_ms' || role === 'admin'));

// 能力评估数据
const form = ref<AbilityAssessmentForm & { elderId?: number, memory?: string, sleep?: string }>({
  id: undefined,
  elderName: undefined,
  assessDate: (() => {
    // 直接使用本地时间并格式化为字符串
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    // 返回格式化的时间字符串 YYYY-MM-DD HH:mm:ss
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  })(),
  selfCare: undefined,
  mobility: undefined,
  eating: undefined,
  dressing: undefined,
  toileting: undefined,
  bathing: undefined,
  cognitive: undefined,
  communication: undefined,
  memory: undefined,
  social: undefined,
  emotion: undefined,
  sleep: undefined,
  totalScore: 0,
  careLevel: undefined,
  assessor: undefined,
  suggestions: undefined,
  remarks: undefined,
  elderId: undefined,
  assessmentUserId: undefined
});

// 表单验证规则
const rules = reactive<FormRules>({
  elderName: [{ required: true, message: '请选择老人', trigger: 'change' }],
  assessDate: [{ required: true, message: '请选择评估日期', trigger: 'change' }],
  assessor: [{ required: true, message: '请输入评估人姓名', trigger: 'blur' }]
});

// 老人选项
const elderOptions = ref<ElderBasicVO[]>([]);
const searchLoading = ref(false);

// 步骤选项
const steps = [
  { title: '基本信息', description: '填写长者的基本信息' },
  { title: '日常生活能力', description: '评估长者的日常生活能力' },
  { title: '个人卫生能力', description: '评估长者的个人卫生能力' },
  { title: '认知与沟通能力', description: '评估长者的认知与沟通能力' },
  { title: '社交与情绪', description: '评估长者的社交与情绪' },
  { title: '评估结果', description: '根据评估结果生成护理建议' }
];

// 当前步骤
const currentStep = ref(isViewMode.value ? 5 : 0); // 查看模式直接显示评估结果页
const progressPercentage = computed(() => {
  return Math.round(((currentStep.value + 1) / steps.length) * 100);
});

// 表单引用
const basicInfoFormRef = ref<FormInstance>();
const dailyLivingFormRef = ref<FormInstance>();
const hygieneFormRef = ref<FormInstance>();
const cognitiveFormRef = ref<FormInstance>();
const socialFormRef = ref<FormInstance>();
const summaryFormRef = ref<FormInstance>();

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 下一步
const nextStep = async () => {
  let isValid = false;

  // 根据当前步骤验证表单
  switch (currentStep.value) {
    case 0: // 基本信息
      await basicInfoFormRef.value?.validate((valid) => {
        isValid = valid;
      });
      break;
    case 1: // 日常生活能力
      isValid = true; // 这些步骤不强制填写所有项
      break;
    case 2: // 个人卫生能力
      isValid = true;
      break;
    case 3: // 认知与沟通能力
      isValid = true;
      break;
    case 4: // 社交与情绪
      isValid = true;
      break;
    default:
      isValid = true;
  }

  if (isValid && currentStep.value < steps.length - 1) {
    currentStep.value++;

    // 如果是进入最后一步，自动计算总分和护理等级
    if (currentStep.value === 5) {
      calculateTotalScore();
      updateCareLevelAndSuggestions();
    }
  } else if (!isValid) {
    proxy?.$modal.msgError('请完成必填项');
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 查看模式下不允许提交
    if (isViewMode.value) {
      return;
    }

    // 确保总分和护理等级已计算
    calculateTotalScore();
    updateCareLevelAndSuggestions();

    // 设置评估用户ID
    form.value.assessmentUserId = Number(userStore.userId);

    // 根据ID判断是添加还是更新
    if (form.value.id) {
      await updateAbilityAssessment(form.value);
      proxy?.$modal.msgSuccess('更新成功');
    } else {
      await addAbilityAssessment(form.value);
      proxy?.$modal.msgSuccess('添加成功');
    }

    // 显示成功信息并开始倒计时
    startCountdown();
  } catch (error) {
    console.error('提交失败', error);
    proxy?.$modal.msgError('提交失败：' + (error instanceof Error ? error.message : String(error)));
    showSuccessMessage.value = false; // 确保失败时不显示成功视图
  }
};

// 取消操作
const cancel = () => {
  try {
    // 使用路由导航返回上一页
    router.back();
  } catch (error) {
    console.error('导航跳转失败', error);
    // 如果返回上一页失败，尝试直接跳转到列表页面
    router.push('/elder_service/abilityAssessment');
  }
};

// 搜索老人
const searchElders = async (query: string = '') => {
  // 如果查询参数为空，则清空选项列表
  if (!query || query.trim() === '') {
    elderOptions.value = [];
    searchLoading.value = false;
    return;
  }

  searchLoading.value = true;

  try {
    const res = await listElderBasic({
      pageNum: 1,
      pageSize: 20,
      elderName: query,
      reviewStatus: '1' // 只查询审核通过的老人
    });
    console.log('获取老人列表成功', res.rows);
    elderOptions.value = res.rows;
  } catch (error) {
    console.error('搜索老人失败', error);
    elderOptions.value = [];
  } finally {
    searchLoading.value = false;
  }
};

// 初始化评估人姓名
const initAssessorName = () => {
  // 如果是护理员用户，自动填入当前用户昵称
  if (isNurseUser.value && !isAdminUser.value && !form.value.assessor) {
    form.value.assessor = userStore.nickname;
  }
};

// 老人变更事件
const handleElderChange = (value: string) => {
  console.log('老人变更:', value);
  const selectedElder = elderOptions.value.find(item => item.elderName === value);
  if (selectedElder) {
    console.log('选中老人信息:', selectedElder);
    form.value.elderId = Number(selectedElder.elderId);
  }
};

// 计算总分
const calculateTotalScore = () => {
  let totalScore = 0;

  // 从每个选项中提取分数
  const extractScore = (value: string | undefined) => {
    if (!value) return 0;
    const match = value.match(/\((\d+)分\)/);
    return match ? parseInt(match[1]) : 0;
  };

  // 计算各项能力得分
  totalScore += extractScore(form.value.selfCare);
  totalScore += extractScore(form.value.mobility);
  totalScore += extractScore(form.value.eating);
  totalScore += extractScore(form.value.dressing);
  totalScore += extractScore(form.value.toileting);
  totalScore += extractScore(form.value.bathing);
  totalScore += extractScore(form.value.cognitive);
  totalScore += extractScore(form.value.communication);
  totalScore += extractScore(form.value.memory);
  totalScore += extractScore(form.value.social);
  totalScore += extractScore(form.value.emotion);
  totalScore += extractScore(form.value.sleep);

  form.value.totalScore = totalScore;
  return totalScore;
};

// 更新护理等级和建议
const updateCareLevelAndSuggestions = () => {
  const totalScore = form.value.totalScore || 0;

  // 根据总分确定护理等级（总分100分）
  if (totalScore >= 90) {
    form.value.careLevel = '完全自理';
    // 始终更新护理建议，确保最新的评估结果反映在建议中
    form.value.suggestions = '长者能力优秀，可以完全自理日常生活，建议定期复查，保持适当运动和社交活动，鼓励参与养老院组织的各类活动。';
  } else if (totalScore >= 75) {
    form.value.careLevel = '基本自理';
    form.value.suggestions = '长者能力良好，基本能自理日常生活，建议定期复查，保持适当运动和社交活动，适当提供生活便利。';
  } else if (totalScore >= 60) {
    form.value.careLevel = '轻度依赖';
    form.value.suggestions = '长者基本能自理，但部分活动需要帮助，建议提供适当辅助和监督，增强日常活动能力训练，定期评估。';
  } else if (totalScore >= 45) {
    form.value.careLevel = '中度依赖';
    form.value.suggestions = '长者多项活动需要帮助，建议提供日常生活辅助，加强功能训练，定期评估健康状况，关注心理健康。';
  } else if (totalScore >= 30) {
    form.value.careLevel = '重度依赖';
    form.value.suggestions = '长者大部分活动需要帮助，建议提供全面照护，关注心理健康，预防并发症，定期医疗评估，加强康复训练。';
  } else if (totalScore >= 15) {
    form.value.careLevel = '严重依赖';
    form.value.suggestions = '长者几乎所有活动都需要帮助，建议提供专业护理，密切监测健康状况，预防压疮等并发症，关注心理健康，提供舒适照护。';
  } else {
    form.value.careLevel = '完全依赖';
    form.value.suggestions = '长者需要全面专业照护，建议提供24小时专业护理，密切监测健康状况，预防各类并发症，关注心理健康，提供舒适照护和临终关怀准备。';
  }
};

// 能力评估得分展示
const abilityScores = computed(() => {
  const extractScore = (value: string | undefined) => {
    if (!value) return 0;
    const match = value.match(/\((\d+)分\)/);
    return match ? parseInt(match[1]) : 0;
  };

  return {
    selfCare: extractScore(form.value.selfCare),
    mobility: extractScore(form.value.mobility),
    eating: extractScore(form.value.eating),
    dressing: extractScore(form.value.dressing),
    toileting: extractScore(form.value.toileting),
    bathing: extractScore(form.value.bathing),
    cognitive: extractScore(form.value.cognitive),
    communication: extractScore(form.value.communication),
    memory: extractScore(form.value.memory),
    social: extractScore(form.value.social),
    emotion: extractScore(form.value.emotion),
    sleep: extractScore(form.value.sleep)
  };
});

// 获取能力标签
const getAbilityLabel = (ability: string) => {
  const labels: Record<string, string> = {
    selfCare: '自理能力',
    mobility: '行动能力',
    eating: '进食能力',
    dressing: '穿衣能力',
    toileting: '如厕能力',
    bathing: '洗澡能力',
    cognitive: '认知能力',
    communication: '沟通能力',
    memory: '记忆力',
    social: '社交能力',
    emotion: '情绪状态',
    sleep: '睡眠质量'
  };
  return labels[ability] || ability;
};

// 获取分数百分比
const getScorePercentage = (score: number) => {
  return (score / 10) * 100;
};

// 获取分数状态
const getScoreStatus = (score: number): 'success' | 'warning' | 'exception' => {
  if (score >= 8) return 'success';
  if (score >= 6) return 'warning';
  return 'exception';
};

// 检查是否为编辑模式
const checkEditMode = async () => {
  const id = route.query.id;
  if (id) {
    try {
      const res = await getAbilityAssessment(id as string);
      Object.assign(form.value, res.data);
    } catch (error) {
      console.error('获取能力评估数据失败', error);
      proxy?.$modal.msgError('获取数据失败');
    }
  }
};

// 组件挂载时初始化
onMounted(() => {
  checkEditMode();
  initAssessorName();
  // 不再预加载老人列表，只在用户输入时搜索
});

// 组件卸载时清理资源
onUnmounted(() => {
  console.log('组件卸载，清理定时器');
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});

const clearTimerAndNavigate = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  // 导航到列表页面
  try {
    router.back();
  } catch (error) {
    console.error('导航跳转失败', error);
    // 如果返回上一页失败，尝试直接跳转到列表页面
    router.push('/elder_service/abilityAssessment');
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 5; // 重置倒计时为5秒
  showSuccessMessage.value = true; // 显示成功视图

  // 清除已存在的定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }

  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearTimerAndNavigate(); // 倒计时结束时导航
    }
  }, 1000); // 每秒减少1
};

// 计算倒计时进度百分比
const countdownPercentage = computed(() => {
  // 避免除以零并处理初始状态
  if (countdown.value <= 0) return 0;
  return (countdown.value / 5) * 100;
});

// 手动返回列表的处理函数
const handleReturnToList = () => {
  clearTimerAndNavigate();
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.step-content {
  min-height: 350px;
  margin-top: 20px;
}

.assessment-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  color: #409EFF;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.assessment-content {
  padding: 10px;
}

.ability-summary {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.ability-item {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.ability-name {
  display: block;
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.assessment-chart {
  margin-top: 30px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.assessment-chart h4 {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 20px;
  text-align: center;
}

.chart-container {
  min-height: 300px;
}

.success-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

.countdown-container {
  margin-top: 20px;
}

.countdown-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
  line-height: 1.2;
}

.mt-4 {
  margin-top: 20px;
}
</style>